package org.sith.gl.taskmanager.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.sith.gl.taskmanager.client.TasksRemoteService;
import org.sith.gl.taskmanager.client.beans.TaskEntityGWT;
import org.sith.gl.taskmanager.client.beans.UserEntityGWT;
import org.sith.gl.taskmanager.server.db.dao.ApplicationContextKeeper;
import org.sith.gl.taskmanager.server.db.dao.TaskEntity;
import org.sith.gl.taskmanager.server.db.dao.UserEntity;
import org.sith.gl.taskmanager.server.db.service.TaskService;
import org.sith.gl.taskmanager.server.db.service.UserService;
import org.sith.gl.taskmanager.server.util.Utils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.UserDetails;


public class TasksRemoteServiceImpl extends RemoteServiceServlet implements TasksRemoteService {
    @Override
    public UserEntityGWT getTasksForCurrentUser() {

        SecurityContext securityContext = (SecurityContext) getThreadLocalRequest().getSession().getAttribute("SPRING_SECURITY_CONTEXT");
        UserDetails principal = (UserDetails) securityContext.getAuthentication().getPrincipal();


        UserService usrService = (UserService) ApplicationContextKeeper.getApplicationContext().getBean("userService");
        UserEntity userEntity = usrService.findByLogin(principal.getUsername());


        if (userEntity == null) {
            throw new IllegalStateException("User not found");
        }
        UserEntityGWT userEntityGWT = Utils.convertToUserGWTEntity(userEntity);
        userEntityGWT.setAssignedEntities(Utils.convertToTaskGWTEntities(userEntity.getAssignedEntities()));
        userEntityGWT.setWritedEntites(Utils.convertToTaskGWTEntities(userEntity.getWritedEntites()));
        return userEntityGWT;
    }

    @Override
    public void saveOrUpdateTask(TaskEntityGWT taskEntityGWT) {
        TaskEntity taskEntity = Utils.convertToTaskDBEntity(taskEntityGWT);
        taskEntity.setAssignedTo(Utils.convertToUserDBEntity(taskEntityGWT.getAssignedTo()));
        taskEntity.setAddedBy(Utils.convertToUserDBEntity(taskEntityGWT.getAddedBy()));

        TaskService taskService = (TaskService) ApplicationContextKeeper.getApplicationContext().getBean("taskService");
        taskService.saveOrUpdate(taskEntity);
    }


}